        var map;

        var markers = [];
        var handles = [];
        var markers_list_html = "<h2>Tags:</h2><br><br>";
        var geocoder;
        var taginlist;
        var SERVERURL = 'http://willyou.bounceme.net:8080/TagInServer/Tagin';
        //var SERVERURL = 'http://localhost:8080/TagInServer/Tagin';
        
        /*
         * HTML5 Location system
         */
        	/*
        	 * On success update input elements
        	 */
	        function success(position) {
	    		//if(s.classname=='success')
	    		//	return
	    		
	    		document.getElementById('input_lat').value=position.coords.latitude
	    		document.getElementById('input_lon').value=position.coords.longitude
	    		panTo()
	    	}
	    	
	    	function error(msg) {
	    	  var s = document.querySelector('#status');
	    	  s.innerHTML = typeof msg == 'string' ? msg : "failed";
	    	  s.className = 'fail';
	    	  
	    	  // console.log(arguments);
	    	}
	    	
	    	/*
	    	 * Request location, send callback methods
	    	 */
	    	if (navigator.geolocation) {
	    		navigator.geolocation.getCurrentPosition(success, error);
	    	} else {
	    		error('not supported');
	    	}
    	/*
    	 * ------html5 location system
    	 */
    	
    	function panTo() {
    		var pos = new google.maps.LatLng(document.getElementById('input_lat').value,document.getElementById('input_lon').value);
    		map.panTo(pos);
    		updateMarkers();
    	}
        
        /*
         * SERVERURL=http://willyou.bounceme.net:8080/TagInServer/Tagin
         * PARAMS=action=list&type=list
         */
        function loadMarkers(SERVERURL,PARAMS) {
	        $.get(SERVERURL+'?'+PARAMS, function(data){
	    		//alert("Data Loaded: " + data);
	    		storeData(data);
	    	});
	    	//ajaxpage("http://willyou.bounceme.net:8080/TagInServer/Tagin","action=list&type=list","details");
        }
        function storeData(data) {
        	taginlist = eval('(' + data + ')');
        }
        
        function updateMarkers(){
        	document.getElementById("range").innerHTML=document.getElementById("input_radious").value;
        	var PARAMS='action=list&type=proximity&lat='+document.getElementById("input_lat").value+'&lon='+document.getElementById("input_lon").value+'&radious='+document.getElementById("input_radious").value;
            
        	//alert(document.getElementById("range").innerHTML+"\n"+PARAMS);
        	
            ajaxpage(SERVERURL,PARAMS,"details");
        }
        
        function ajaxpage(url,params,contentid){
            var page_request = false;
            if (window.XMLHttpRequest) // if Mozilla, Safari etc
                    page_request = new XMLHttpRequest();
            else if (window.ActiveXObject){ // if IE
                    try {
                            page_request = new ActiveXObject("Msxml2.XMLHTTP");
                    }
                    catch (e){
                            try{
                                    page_request = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            catch (e){}
                    }
            }
            else
                    return false;

            if(url!='' && params!=''){
            		deleteOverlays();
            	
                    page_request.open('get', url+'?'+params);

                    page_request.onreadystatechange=function(){
                            if (page_request.readyState == 4){
                            	document.getElementById(contentid).innerHTML="Loading data ...";
                            	
                            	var results=page_request.responseText;
                            	taginlist = JSON.parse(results);
                            	
                        		//if(taginlist.length>0 && taginlist[0].name!='undefined'){
                            		/*
						             * Problemas com variaveis globais .. grr .. por isso adiciono marcadores aqui
						             */
						            document.getElementById(contentid).innerHTML = "";
						            for (var variable=0;variable<=taginlist.length;variable++){
						            	if(taginlist[variable]!=null && taginlist[variable].lat!=null && taginlist[variable].lon!=null) {
						            		var tagicon = new google.maps.MarkerImage('images/'+taginlist[variable].category+'.png',
					                                new google.maps.Size(50,50),
					                                new google.maps.Point(0,0),
					                                new google.maps.Point(50,50)
					                        );
						            		
							            	var marker = new google.maps.Marker({
						                        map: map,
						                        icon: tagicon,
						                        position: new google.maps.LatLng(taginlist[variable].lat,taginlist[variable].lon),
						                        title:taginlist[variable].name
						                	});
						                	
						                	//alert("Nome: " + taginlist[variable].name + ", " + "Categoria: "+taginlist[variable].category+", "+"Criado por: "+taginlist[variable].owner+"\n\n"+taginlist[variable].info);
						                	
							            	var contentString = '<div id="content" style="width: 250px; height: 200px;">'+
			                                            '<div id="siteNotice">'+
			                                            '</div>'+
			                                            '<div id="bodyContent" style="width: 100%; height: 100%;">'+
			                                            '<br/><font size="5em">' + taginlist[variable].name + '</font><br/>'+
			                                            '<font size="3">' + taginlist[variable].info + '</font><br />'+
			                                            '<font size="2"><strong>Criado por:</strong> ' + taginlist[variable].owner + '</font>'+
			                                            '</div>'+
		                                            '</div>';
		                                    
							            	attachMessage(marker, taginlist[variable].name, contentString);
						                	
							            	/*
							            	 * lista de links com mapeamento para os marcadores atraves da funcao myclick(i)
							            	 */
						                	document.getElementById("details").innerHTML += '<a href="#content" onclick="myclick(' + variable + ')">' + taginlist[variable].name + '<\/a><br>';
						                	//document.getElementById(contentid).innerHTML += "<br/>Nome: " + taginlist[variable].name + "<br/>Categoria: "+taginlist[variable].category+", "+"Criado por: "+taginlist[variable].owner+"<br/><br/>"+taginlist[variable].info + "<br/>" + taginlist[variable].lat + "," + taginlist[variable].lon + "<br/><br/>";
						            	}
					                }
                            	/*}else{
                            		document.getElementById(contentid).innerHTML = "Não existem Tags perto da sua localização.<br>"+taginlist;
                            	}*/
                            }
                    }

                    page_request.send(null)
            }else
                document.getElementById(contentid).innerHTML=""
        }
        
        function initialize() {
        		geocoder = new google.maps.Geocoder();
                var mapCenter = new google.maps.LatLng(document.getElementById("input_lat").value,document.getElementById("input_lon").value);

                var mapOptions = {
                        zoom: 16,
                        zoomControl: true,
                        zoomControlOptions: {
                            style: google.maps.ZoomControlStyle.SMALL
                        },
                        mapTypeControl: true,
                        mapTypeControlOptions: {
                            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
                        },
                        scaleControl: false,
                        streetViewControl: false,
                        center: mapCenter,
                        //ROADMAP, SATELLITE, HYBRID, TERRAIN
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                //criar o mapa na div "map_canvas"
                map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
                
                google.maps.event.addListener(map, 'mouseup', function() {
                	var newCenter = map.getCenter();
                	
                	/*
                	 * Limpar iterativamente os listeners [tags]
                	for(listenerHandle in handles) {
                		google.maps.event.removeListener(listenerHandle);
                	}
                	*/
                	
                	deleteOverlays();
                	
                	/*
                	 * Limpar todos os listeners [tags]
                	 */
                	//google.maps.event.clearListeners(map, 'click');
                	
	                markers = []
                	markers_list_html = "";
                	
                	document.getElementById("input_lat").value=newCenter.lat();
                	document.getElementById("input_lon").value=newCenter.lng();
                	
                	var PARAMS='action=list&type=proximity&lat='+newCenter.lat()+'&lon='+newCenter.lng()+'&radious='+document.getElementById("input_radious").value;
                    
                    ajaxpage(SERVERURL,PARAMS,"details");
                });
                
                var PARAMS='action=list&type=proximity&lat='+document.getElementById("input_lat").value+'&lon='+document.getElementById("input_lon").value+'&radious='+document.getElementById("input_radious").value;
                
                ajaxpage(SERVERURL,PARAMS,"details");
                
                /*
                document.getElementById("details").innerHTML = markers_list_html;
                
                for (var variable=0;variable<=taginlist.length;variable++){
                	var marker = new google.maps.Marker({
                        map: map,
                        position: new google.maps.LatLng(taginlist[variable].lat,taginlist[variable].lon),
                        title:taginlist[variable].name
                	});
                	
                	alert("Nome: " + taginlist[variable].name + ", " + "Categoria: "+taginlist[variable].category+", "+"Criado por: "+taginlist[variable].owner+"\n\n"+taginlist[variable].info);
                	attachMessage(marker, taginlist[variable].name, "Categoria: "+taginlist[variable].category+", "+"Criado por: "+taginlist[variable].owner+"\n\n"+taginlist[variable].info);
                }
                */
                
                //google.maps.event.trigger(marker, "click");
                // Create the DIV to hold the control and call the HomeControl() constructor
                // passing in this DIV.
                /*
                var homeControlDiv = document.createElement('DIV');
                var homeControl = new HomeControl(homeControlDiv, map);
                
                homeControlDiv.index = 1;
                map.controls[google.maps.ControlPosition.RIGHT_TOP].push(homeControlDiv);
                */
    }

    function attachMessage(marker, name, msg) {
            var infowindow = new google.maps.InfoWindow(
                    {
                    	content: msg,
                    	//size: new google.maps.Size(50,50)
                    });
            
            google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map,marker);
            });
            
            markers.push(marker);
            markers_list_html += '<a href="#content" onclick="myclick(' + (markers.length-1) + ')">' + name + '<\/a><br>';
    }
    
    function myclick(i) {
        document.getElementById("details").innerHTML ="<p><h2>"+taginlist[i].name+"</h2>"+
                //"Categoria: "+taginlist[i].category+"<br>"+
                "Criado por: "+taginlist[i].owner+"<br>"+
                "Informação: "+taginlist[i].info+"<br>"+
                "Localização: "+taginlist[i].lat+","+taginlist[i].lon+
                "</p><br>";
        
        document.getElementById("details").innerHTML += markers_list_html;
        
        google.maps.event.trigger(markers[i], "click");
    }
	
	/**
	* The HomeControl adds a control to the map that simply
	* returns the user to Chicago. This constructor takes
	* the control DIV as an argument.
	*/
	function HomeControl(controlDiv, map) {
		// Set CSS styles for the DIV containing the control
		// Setting padding to 5 px will offset the control
		// from the edge of the map
		controlDiv.style.padding = '5px';
		
		// Set CSS for the control border
		var controlUI = document.createElement('DIV');
		controlUI.style.backgroundColor = 'white';
		controlUI.style.borderStyle = 'solid';
		controlUI.style.borderWidth = '2px';
		controlUI.style.cursor = 'pointer';
		controlUI.style.textAlign = 'center';
		controlUI.title = 'Click to set the map to Home';
		controlDiv.appendChild(controlUI);
		
		// Set CSS for the control interior
		var controlText = document.createElement('DIV');
		controlText.style.fontFamily = 'Arial,sans-serif';
		controlText.style.fontSize = '12px';
		controlText.style.paddingLeft = '4px';
		controlText.style.paddingRight = '4px';
		controlText.innerHTML = markers_list_html;
		controlUI.appendChild(controlText);
		
		//Setup the click event listeners
		//google.maps.event.addDomListener(controlUI, 'click', function() {
		//  map.setCenter()
		//});
	}
	
	function codeAddress() {
        var address = document.getElementById("address").value;
        geocoder.geocode( {'address': address}, function(results, status) {
                if(status == google.maps.GeocoderStatus.OK) {
                	//center map on the address supplied
                    map.setCenter(results[0].geometry.location); 
                    //update the markers to meet the new location
                    var newCenter = map.getCenter();
                    document.getElementById('input_lat').value=newCenter.lat();
    	    		document.getElementById('input_lon').value=newCenter.lng();
                    updateMarkers();
                }else{
		            alert("Geocode was not successful for the following reason: " + status);
		        }
		});
	}
	
	// Removes the overlays from the map, but keeps them in the array
	function clearOverlays() {
	  if (markers) {
	    for (i in markers) {
	      markers[i].setMap(null);
	    }
	  }
	}

	// Shows any overlays currently in the array
	function showOverlays() {
	  if (markers) {
	    for (i in markers) {
	      markers[i].setMap(map);
	    }
	  }
	}

	// Deletes all markers in the array by removing references to them
	function deleteOverlays() {
	  if (markers) {
	    for (i in markers) {
	      markers[i].setMap(null);
	    }
	    markers.length = 0;
	  }
	}
	